import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'

const loadLocalRoutes = () => {
  const localRoutes: RouteRecordRaw[] = [] // 保存所有需要动态添加的路由
  // 读取所有的router/main下的路由文件；第二个参数eager为让获取到的结果成一个module，结果如下
  // ../../router/main/analysis/dashboard/dashboard.ts: Module {Symbol(Symbol.toStringTag): 'Module'}
  // const files = import.meta.glob('../../router/main/**/*.ts', { eager: true })
  const files: Record<string, any> = import.meta.glob('@/router/main/**/*.ts', { eager: true })
  // console.log(files)
  for (const key in files) {
    // key为files结果中的文件路径
    const module = files[key]
    //console.log(module.default) // {path: '/main/system/role', name: 'role', children: Array(0), component: ƒ}
    localRoutes.push(module.default)
  }
  return localRoutes
}

export let firstMenu:any = null

export const mapMenusToRoutes = (userMenus: any[]) => {
  const localRoutes = loadLocalRoutes()
  const routes: RouteRecordRaw[] = []

  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRoutes.find((item) => item.path === submenu.url)
      if(route) {
        // 给route的顶层菜单加重定向功能（但是只需要添加一次）
        if(!routes.find(item =>item.path === menu.url)) {
          routes.push({path:menu.url, redirect: route.path})
        }
        routes.push(route)
      }
      // 记录第一个被匹配的菜单
      if(!firstMenu && route) firstMenu = submenu
    }
  }
  return routes
}

/**
 * 根据路径去匹配需要显示的菜单（当用户进入main页面，默认选中当前用户的第一个菜单；当选中其他菜单后，一刷新选中状态又回到第一个菜单）
 * @param path 需要匹配的路径
 * @param userMenus 所有的菜单
 */
export function mapPathToMenu(path:string, userMenus:any[]) {
  for(const menu of userMenus) {
    for(const submenu of menu.children) {
      if(submenu.url === path) {
        return submenu
      }
    }
  }
}

interface IBreadCrumbs {
  name: string
  path: string
}
export function mapPathToBreadCrumbs(path:string, userMenus:any[]) {
  const breadcrumbs:IBreadCrumbs[]  = []
  for(const menu of userMenus) {
    for(const submenu of menu.children) {
      if(submenu.url === path) {
        breadcrumbs.push({name:menu.name, path:menu.url})
        breadcrumbs.push({name: submenu.name, path: submenu.url})
      }
    }
  }
  // console.log(breadcrumbs)
  return breadcrumbs
}